import serial
import paho.mqtt.client as mqtt
import binascii
import subprocess
import os
import time
from threading import Timer
import testslip
import socket
from fcntl import fcntl,F_GETFL,F_SETFL
from MCURecvAndDSPSend import *

amixer = 0
#timer_interval=0.0008
timer_interval=0.0008
p=subprocess.Popen(["linphonec", "-b", "/root/mylinphonerc","-a"],
                       stdin=subprocess.PIPE,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE,
                       universal_newlines=True)
flags = fcntl(p.stdout,F_GETFL)
fcntl(p.stdout,F_SETFL,flags|os.O_NONBLOCK)

baudrate = os.popen('cat /root/savebaudrate').read()
baudrate = int(baudrate)
ser = serial.Serial('/dev/ttyO3', 38400, timeout=1)
ser1 = serial.Serial('/dev/ttyO1', baudrate, timeout=1)
ser2 = serial.Serial('/dev/ttyO2',baudrate,timeout=1)
mcuRecvAndDspSend = MCURecvAndDSPSend()
if baudrate == 38400:
    mcuRecvAndDspSend.isEnglish = True
else:
    mcuRecvAndDspSend.isEnglish = False
def splitByWidth(string,width):
    return [string[x:x+width] for x in range(0,len(string),width)]
def delayrun():
    global p
    global ser
    global ser1
    global ser2
    global amixer
    global baudrate
    global mcuRecvAndDspSend
    strTemp = ser.readall()
    width = 100
    slipModel = testslip.slip()
    if binascii.b2a_hex(strTemp)!='':
        try:
            print(binascii.b2a_hex(strTemp))
            #slipModel=testslip.slip()
            slipModel.stream = strTemp
            strdecode = slipModel.decode()
            strdecode = strdecode[0]
            if strdecode.find('\x90') == 2:
                resultcode = testslip.analysisfunc(strTemp,p,ser1,ser2)
                print(binascii.b2a_hex(resultcode))
                if resultcode!='linphone':
                    ser.write(str(resultcode))
            elif strdecode.find('\x60\x80') == 2 or strdecode.find('\x60\x40') == 2:
                mcuRecvAndDspSend.recvMCU(strdecode)
            else:
                arr = splitByWidth(binascii.b2a_hex(strTemp),width)
                for x in range(len(arr)):
                    client.publish("tty1r",arr[x])
        except Exception,ex:
            print Exception,":",ex
            arr = splitByWidth(binascii.b2a_hex(strTemp),width)
            for x in range(len(arr)):
                client.publish("tty1r",arr[x])
    strTemp1 = binascii.b2a_hex(ser2.readall())
    if strTemp1!='':

        print(strTemp1)
        arr = splitByWidth(strTemp1,width)
        for x in range(len(arr)):
            client.publish("tty3r",arr[x])
    strTemp2 = binascii.b2a_hex(ser1.readall())
    if strTemp2!='' or mcuRecvAndDspSend.dataFromMCU!='':
        if strTemp2 != '':
            print(strTemp2)
        code,messageArr = mcuRecvAndDspSend.handleMessage(strTemp2)
        if code == 1:
            for bytes in messageArr:
                bytes = slipModel.encode(bytes)
                print binascii.b2a_hex(bytes)
                ser1.write(str(bytes))
        elif code == 2:
            for message in messageArr:
                message = slipModel.encode(message)
                arr = splitByWidth(message, width)
                for x in range(len(arr)):
                    client.publish("tty2r", arr[x])
        elif code == 3:
            for message in messageArr:
                message = slipModel.encode(message)
                ser.write(str(message))
    try:
        outPutLines = os.read(p.stdout.fileno(),1024)
        if outPutLines.find('2') == 15:
            os.system('echo 1 > /sys/class/gpio/gpio5/value')
        elif outPutLines.find('3') == 15:
            os.system('echo 0 > /sys/class/gpio/gpio5/value')
        elif outPutLines.find('Media stream established')!=-1:
            ser.write('answering')
        elif outPutLines.find('ended')!=-1:
            ser.write('ended')
        elif outPutLines.find('error')!=-1:
            ser.write('error')
        else:
            print outPutLines
            if amixer >= 0:
                os.system("amixer cset numid=7 1")
                os.system("amixer cset numid=7 0")
            amixer+=1
    except OSError:
        1==1
    Timer(timer_interval,delayrun).start()

def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    client.subscribe("tty1t")
    client.subscribe("tty2t")
    client.subscribe("tty3t")
    client.subscribe("ptt")
def on_message(client, userdata, msg):
    #global pttFlag
    print(msg.topic+" "+binascii.b2a_hex(str(msg.payload)))
    if msg.topic == "tty1t":
        ser.write(str(msg.payload))
    elif msg.topic == "tty2t":
        ser1.write(str(msg.payload))
    elif msg.topic == "tty3t":
        ser2.write(str(msg.payload))
    elif msg.topic == "ptt":
        #if pttFlag == False:
            #os.system("amixer cset numid=7 1")
            #os.system("amixer cset numid=7 0")
            #pttFlag=True
        if str(msg.payload)=="push":
            os.system("echo 0 > /sys/class/gpio/gpio5/value")
        else:
            os.system("echo 1 > /sys/class/gpio/gpio5/value")
if __name__ == '__main__':
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    serverAddress = os.popen('cat /root/sipserver').read().strip()
    print serverAddress
    accountInfo = os.popen('cat /root/accountInfo').read().strip().split('\n')
    accountName = accountInfo[0]
    accountPwd = accountInfo[1]
    setCommand = 'register sip:'+accountName+'@'+serverAddress+' '+serverAddress+' '+accountPwd+'\n'
    p.stdin.write('ungister')
    p.stdin.write(setCommand)
    try:
        ser.timeout=0.0001
        ser1.timeout=0.0001
        ser2.timeout=0.0001
        try:
            client.connect(serverAddress, 1883, 60)
        except Exception:
            client.connect("127.0.0.1", 1883, 60)
        os.system("echo 5 > /sys/class/gpio/export")
        os.system("echo 1 > /sys/class/gpio/gpio5/value")
        os.system("echo out > /sys/class/gpio/gpio5/direction")
        os.system("echo 1 > /sys/class/gpio/gpio5/value")
        os.system("amixer cset numid=7 1")
        os.system("amixer cset numid=7 0")
        t=Timer(timer_interval,delayrun)
        t.start()
        ser.write(str(binascii.a2b_hex('c00009009009030301a9c0')))
        address = ('10.102.11.136', 9999)  
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.sendto("finished", address)
        client.loop_forever()
    except KeyboardInterrupt:
        client.disconnect()
        ser.close()


